package com.ruoyi.web.controller.Order;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.Goods.domain.Goods;
import com.ruoyi.Goods.service.IGoodsService;
import com.ruoyi.HbUser.domain.HbUser;
import com.ruoyi.HbUser.service.IHbUserService;
import com.ruoyi.Money.domain.Money;
import com.ruoyi.Money.service.IMoneyService;
import com.ruoyi.Order.domain.Order;
import com.ruoyi.Order.service.IOrderService;
import com.ruoyi.OrderGoods.domain.OrderGoods;
import com.ruoyi.OrderGoods.service.IOrderGoodsService;
import com.ruoyi.School.domain.School;
import com.ruoyi.School.service.ISchoolService;
import com.ruoyi.User.domain.User;
import com.ruoyi.User.service.IUserService;
import com.ruoyi.User.wxpay.WechatExtract;
import com.ruoyi.UserAddress.domain.UserAddress;
import com.ruoyi.UserAddress.service.IUserAddressService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.APPConstants;
import com.ruoyi.common.utils.DateTools;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.PhoneLoginService;
import com.ruoyi.web.controller.PhoneLogin.PhoneLoginController;
import com.ruoyi.web.controller.qqLoginAndPayByHTQ.QQPayExtract;

/**
 * 订单 信息操作处理
 *
 * @author ruoyi
 * @date 2019-07-15
 */
@Controller
@RequestMapping("/Order/verifyOrder")
public class VerifyOrderController extends BaseController
{
    private String prefix = "Order/verifyOrder";

	@Autowired
	private IOrderService orderService;

	@Autowired
	private IGoodsService goodsService;

	@Autowired
    private ISysUserService sysUserService;

	@Autowired
	private IHbUserService hbUserService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IOrderGoodsService orderGoodsService;

	@Autowired
	private PhoneLoginService nsService;

	@Autowired
	private IUserAddressService userAddressService;

	@Autowired
	private IMoneyService moneyService;

	@Autowired
	private ISchoolService schoolService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private PhoneLoginController weixin;




    //private Double startFeeForCoin=10*startFee;


	@RequiresPermissions("Order:order:view")
	@GetMapping()
	public String order()
	{
	    return prefix + "/order";
	}

	/**
	 * 查询订单列表
	 */
	@RequiresPermissions("Order:order:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Order order)
	{
		String deptId=getDeptId();
		if(!"100".equals(deptId)){
			order.setDeptId(Integer.parseInt(deptId));
		}
		order.setValid(1);
		order.setOrderShuxin(APPConstants.ORDER_SHUXING_TUIKUAN);
		order.setReturnOperate(0);
		startPage();
        List<Order> list = orderService.selectOrderList(order);
		return getDataTable(list);
	}


	/**
	 * 导出订单列表
	 */
	@RequiresPermissions("Order:order:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Order order)
    {
    	List<Order> list = orderService.selectOrderList(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        return util.exportExcel(list, "order");
    }

	/**
	 * 新增订单
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}

	@PostMapping("/goodsList")
	@ResponseBody
	public TableDataInfo goodsList(Order order)
	{
		Integer id=order.getId();
		startPage();
		List<Order> list = orderService.selectOrderGoodsList(id);
		if((list.size()==0)||(list.get(0)==null)){
			list=Collections.EMPTY_LIST;
		}
		return getDataTable(list);
	}
	/**
	 * 新增保存订单
	 */
	@RequiresPermissions("Order:order:add")
	@Log(title = "订单", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(Order order)
	{
		return toAjax(orderService.insertOrder(order));
	}

	/**
	 * 修改订单
	 */
	/**
	 * @param id
	 * @param mmap
	 * @return
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
		Order order = orderService.selectOrderById(id);
		String jiadanId = order.getJiadanId();
		if (!StringUtils.isEmpty(jiadanId)) {
			int jiadanidToInt = Integer.parseInt(jiadanId);
			Order example = new Order();
			example.setId(jiadanidToInt);
			List<Order> orderList = orderService.selectOrderList(example);
			if (orderList.size() > 0) {
				Order jiadanOrder = orderList.get(0);
				mmap.put("jiadanOrder", jiadanOrder);
			} else {
				mmap.put("jiadanOrder", new Order());
			}
		} else {
			mmap.put("jiadanOrder", new Order());
		}
		String addressId = order.getAddressId();
		UserAddress userAddress = new UserAddress();
		if(!StringUtils.isEmpty(addressId)){
			int addressIdToInt = Integer.parseInt(addressId);
			userAddress = userAddressService
					.selectUserAddressByIdChinese(addressIdToInt);
		}
		mmap.put("userAddress", userAddress==null?new UserAddress():userAddress);
		Integer qishouId = order.getQishouId();
		User riderUser =new User();
		if(qishouId!= null){
			riderUser = userService.selectUserById(qishouId);
		}
		mmap.put("riderUser", riderUser==null?new User():riderUser);
		mmap.put("order", order);
		return prefix + "/edit";
	}

	@GetMapping("/detail/{id}")
	public String detail(@PathVariable("id") Integer id, ModelMap mmap)
	{
		Order order = orderService.selectOrderById(id);
		mmap.put("order", order);
	    return prefix + "/detail";
	}

	/**
	 * 修改保存订单
	 */
	@RequiresPermissions("Order:order:edit")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Order order)
	{
		return toAjax(orderService.updateOrder(order));
	}

	/**
	 * 删除订单
	 */
	@RequiresPermissions("Order:order:remove")
	@Log(title = "订单", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		return toAjax(orderService.deleteOrderByIds(ids));
	}

	/**
	 * 订单审核 同意申请
	 * @throws Exception
	 */
	@PostMapping("/updateStatus")
	@ResponseBody
	public AjaxResult updateStatus(String id) throws Exception {
		//部门ID
	    String shirodeptId=getDeptId();
		/* 根据订单判断退货类型 */
		//PhoneLoginController weixin = new PhoneLoginController();
		int realId = Integer.parseInt(id);
		Order orderPersist = orderService.selectOrderById(Integer.parseInt(id));
		String orderNo=orderPersist.getOrderid();
		//获取配送费
		Double startFee;
		long l = Long.valueOf(shirodeptId).longValue();
		SysDept dept=deptService.selectDeptById(l);
		if(!"100".equals(shirodeptId)){
			int idschool=dept.getSchoolId();
			School persistSchool=schoolService.selectSchoolById(idschool);
			startFee=persistSchool.getStartFee();
		} else {
			startFee = (double)0;
		}
		Integer isMoney=orderPersist.getIsMoney();
		//骑手ID,判断是否接单
		Integer riderId=orderPersist.getQishouId();
		int deptId = 0;
		if (orderPersist.getDeptId() != null) {
			deptId = orderPersist.getDeptId();
		}
		int userId = orderPersist.getUserId();
		Integer qishouId=orderPersist.getQishouId();
		String orderNum = orderPersist.getOrderid();
		String toUserSuccess = "您申请的退款订单已通过！";
		String toRiderSuccess = "您接的" + orderNum + "订单已被退款成功";
		if (orderPersist.getReturnType() != null
				&& orderPersist.getReturnType() != "") {
			String returType = orderPersist.getReturnType();
			if (returType.equals("1")) {
				/* 退货退款的情况 */
				/* 退回商品销量和库存数量 */

				OrderGoods oGoods = new OrderGoods();
				oGoods.setOrderId(realId);
				List<OrderGoods> OrderGoodslist = orderGoodsService
						.selectOrderGoodsList(oGoods);
				if (OrderGoodslist.size() > 0) {
					for (OrderGoods example : OrderGoodslist) {
						Integer num = example.getNum();
						Integer goodsId = example.getGoodsId();
						Goods persist = goodsService.selectGoodsById(goodsId);
						if (persist != null && persist.getGoodsNum() != null) {
							Integer goodsNum = persist.getGoodsNum();
							Integer goodsXl = persist.getGoodsXl();
							/* 修改库存 */

							goodsNum = goodsNum + num;
							/* 修改销量 */
							if (goodsXl != null) {
								goodsXl = goodsXl - num;
							} else {
								goodsXl = 0;
							}
							persist.setGoodsNum(goodsNum);
							persist.setGoodsXl(goodsXl);
							persist.setModifyBy(ShiroUtils.getSysUser()
									.getUserName());
							persist.setModifyDate(DateUtils.getNowDate());
							goodsService.updateGoods(persist);
						}
					}
				}

				/* 退回用户金币、余额以及红包(包括小费和跑腿费) */

				/* 找到用户当前金额 */
				User userPersist = userService.selectUserById(userId);
				double credit1 = userPersist.getCredit1().doubleValue();
				BigDecimal userBeforeMoney = userPersist.getCredit1();
				double credit2 = userPersist.getCredit2().doubleValue();
				BigDecimal userBeforeCoin = userPersist.getCredit2();

				double backCredit1 = (double)0;/* 用户余额退回金额 */
				double backCredit2 = (double)0;/* 用户金币退回金额 */
				//BigDecimal weixinMoney = new BigDecimal(0);/* 用户微信支付退回金额 */

				/* 找到并修改订单金额流向 */
				Money moneyExample = new Money();
				moneyExample.setOrderId(realId);
				List<Money> moneyList = moneyService
						.selectMoneyList(moneyExample);
				for (Money moneyPersistIndex : moneyList) {
					String jiLu=moneyPersistIndex.getJilu();
					if("微信支付退回".equals(jiLu)||"订单退货金币退回".equals(jiLu)||"订单退货余额退回".equals(jiLu)||"佣金退回".equals(jiLu)||"QQ支付退回".equals(jiLu)){
						return AjaxResult.error("操作失败");
					}
				}
				if (moneyList.size() > 0 && moneyList != null) {
					for (Money moneyPersist : moneyList) {
						String payWay = moneyPersist.getPayWay();
						String record=moneyPersist.getJilu();
						if ("5001".equals(payWay)) {
							/* 微信支付 退回到用户账户余额中 */
							Double jine = moneyPersist.getJine();
							jine=-jine;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine=jine-startFee;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine=(double) 0;
								}
							}

							String trueJine = jine.toString();
							//weixinMoney = weixinMoney.subtract(Decimaljine);
							/* 微信支付 退回 */
							int thisUserId = moneyPersist.getUserId();
							User userCurrent = userService
									.selectUserById(thisUserId);
							String openId=userCurrent.getOpenidWa();
							String desc="微信支付退回";

							String a = WechatExtract.deptToUser(trueJine, openId, desc, id);

							/* 插入微信支付退回记录 */
							Money currentMoney = new Money();
							currentMoney.setOrderId(realId);
							currentMoney.setUserId(thisUserId);
							currentMoney.setJine(jine);
							currentMoney.setJilu("微信支付退回");
							currentMoney.setPayWay("5001");
							currentMoney.setValid(1);
							currentMoney.setCreactDate(DateUtils.getNowDate());
							currentMoney.setCreateBy(ShiroUtils.getSysUser()
									.getUserName());
							moneyService.insertMoney(currentMoney);


						}

						if ("5008".equals(payWay)) {
							/* QQ支付 退回到用户账户余额中 */
							Double jine = moneyPersist.getJine();
							jine=-jine;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine=jine-startFee;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine=(double) 0;
								}
							}

							String trueJine = jine.toString();
							//weixinMoney = weixinMoney.subtract(Decimaljine);
							/* 微信支付 退回 */
							int thisUserId = moneyPersist.getUserId();
							User userCurrent = userService
									.selectUserById(thisUserId);
							String openId=userCurrent.getOpenidWa();
							String desc="QQ支付退回";

							String a = QQPayExtract.deptToUser(trueJine, openId, desc, orderNo);

							/* 插入QQ支付退回记录 */
							Money currentMoney = new Money();
							currentMoney.setOrderId(realId);
							currentMoney.setUserId(thisUserId);
							currentMoney.setJine(jine);
							currentMoney.setJilu("QQ支付退回");
							currentMoney.setPayWay("5008");
							currentMoney.setValid(1);
							currentMoney.setCreactDate(DateUtils.getNowDate());
							currentMoney.setCreateBy(ShiroUtils.getSysUser()
									.getUserName());
							moneyService.insertMoney(currentMoney);


						}
						if ("5002".equals(payWay)) {
							/* 余额支付 退回到用户账户余额中 */
							Double jine2 = moneyPersist.getJine();
							jine2=-jine2;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine2=jine2-startFee;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine2=(double) 0;
								}
							}
							credit1=credit1+jine2;
							backCredit1=backCredit1+jine2;
						}
						if ("5003".equals(payWay)) {
							/* 金币支付 退回到用户金币余额中 */
							Double jine3 = moneyPersist.getJine();
							jine3=-jine3;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine3=jine3-startFee*10;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine3=(double) 0;
								}
							}
							credit2=credit2+jine3;
							backCredit2=backCredit2+jine3;
						}
						if ("5006".equals(payWay)) {
							/* 帮圈佣金 退回 */
							Double jine4 = moneyPersist.getJine();
							int thisUserId = moneyPersist.getUserId();

							/* 修改用户佣金 */
							User userCurrent = userService
									.selectUserById(thisUserId);
							Double commisson = userCurrent.getCommission();
							commisson = commisson - jine4;
							userCurrent.setCommission(commisson);
							userService.updateUser(userCurrent);

							/* 插入佣金退回记录 */
							Money currentMoney = new Money();
							currentMoney.setOrderId(realId);
							currentMoney.setUserId(thisUserId);
							currentMoney.setJine(-jine4);
							currentMoney.setJilu("佣金退回");
							currentMoney.setPayWay("5006");
							currentMoney.setValid(1);
							currentMoney.setNowMoney(commisson.toString());
							currentMoney.setCreactDate(DateUtils.getNowDate());
							currentMoney.setCreateBy(ShiroUtils.getSysUser()
									.getUserName());
							moneyService.insertMoney(currentMoney);
						}
					}
					/* 退回订单余额金额大于0 往money表插入记录 */
					if (backCredit1>0) {
						Money moneyPersist1 = new Money();
						moneyPersist1.setOrderId(realId);
						moneyPersist1.setUserId(userId);
						moneyPersist1.setJine(backCredit1);
						moneyPersist1.setPayWay("5002");
						moneyPersist1.setValid(1);
						moneyPersist1.setJilu("订单退货余额退回");
						moneyPersist1.setNowMoney(String.valueOf(credit1));
						moneyPersist1.setCreactDate(DateUtils.getNowDate());
						moneyPersist1.setCreateBy(ShiroUtils.getSysUser()
								.getUserName());
						moneyService.insertMoney(moneyPersist1);
					}

					/* 退回订单金币金额大于0 往money表插入记录 */
					if (backCredit2>0) {
						Money moneyPersist2 = new Money();
						moneyPersist2.setOrderId(realId);
						moneyPersist2.setUserId(userId);
						moneyPersist2.setJine(backCredit2);
						moneyPersist2.setPayWay("5003");
						moneyPersist2.setJilu("订单退货金币退回");
						moneyPersist2.setNowMoney(String.valueOf(credit2));
						moneyPersist2.setValid(1);
						moneyPersist2.setCreactDate(DateUtils.getNowDate());
						moneyPersist2.setCreateBy(ShiroUtils.getSysUser()
								.getUserName());
						moneyService.insertMoney(moneyPersist2);
					}
					userPersist.setCredit1(new BigDecimal(credit1));
					userPersist.setCredit2(new BigDecimal(credit2));
					userPersist.setUpdateBy(ShiroUtils.getSysUser()
							.getUserName());
					userPersist.setUpdateTime(DateUtils.getNowDate());
					userService.updateUser(userPersist);



				}

				/* 退回红包 */
				Integer HbId = orderPersist.getPacketsId();
				if (HbId != null) {
					HbUser hbUser = hbUserService.selectHbUserById(HbId);
					if (hbUser != null) {
						hbUser.setValid(1);
						hbUser.setModifyDate(DateUtils.getNowDate());
						hbUserService.updateHbUser(hbUser);
					}
				}





				/* 修改订单退款状态与审核时间 */
				Order persistOrder = orderService.selectOrderById(realId);
				//persistOrder.setOrderShuxin(String.valueOf(2005));
				persistOrder.setReturnOperate(1);
				persistOrder.setPassDate(DateTools.getYMDhms());
				persistOrder.setModifyBy(ShiroUtils.getSysUser().getUserName());
				persistOrder.setModifyDate(DateTools.getYMDhms());
				persistOrder.setOrderShuxin("2008");
				//0901更新 退款时候，不调用相应方法
//				weixin.fxx_now(String.valueOf(userId), orderNum, toUserSuccess);
//				if(riderId!=null){
//					weixin.fxx_now(String.valueOf(riderId), orderNum,
//							toRiderSuccess);
//				}

				return toAjax(orderService.updateOrder(persistOrder));
				//return toAjax(2);
			} else if (returType.equals("2")) {
				/* 仅退款的情况 */

				/* 找到用户当前金额 */
				User userPersist = userService.selectUserById(userId);
				double credit1 = userPersist.getCredit1().doubleValue();
				double credit2 = userPersist.getCredit2().doubleValue();

				double backCredit1 = (double)0;/* 用户余额退回金额 */
				BigDecimal userBeforeMoney = userPersist.getCredit1();
				double backCredit2 = (double)0;/* 用户金币退回金额 */

				/* 找到并修改订单金额流向 */
				Money moneyExample = new Money();
				moneyExample.setOrderId(realId);
				List<Money> moneyList = moneyService
						.selectMoneyList(moneyExample);
				for (Money moneyPersistIndex : moneyList) {
					String jiLu=moneyPersistIndex.getJilu();
					if("微信支付退回".equals(jiLu)||"订单退货金币退回".equals(jiLu)||"订单退货余额退回".equals(jiLu)||"佣金退回".equals(jiLu)){
						return AjaxResult.error("操作失败");
					}
				}
				if (moneyList.size() > 0 && moneyList != null) {
					for (Money moneyPersist : moneyList) {

						String payWay = moneyPersist.getPayWay();
						String record=moneyPersist.getJilu();
						if ("5001".equals(payWay)) {
							/* 微信支付 退回到用户账户余额中 */
							Double jine = moneyPersist.getJine();
							jine=-jine;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine=jine-startFee;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine=(double) 0;
								}
							}

							String trueJine = jine.toString();
							//weixinMoney = weixinMoney.subtract(Decimaljine);
							/* 微信支付 退回 */
							int thisUserId = moneyPersist.getUserId();
							User userCurrent = userService
									.selectUserById(thisUserId);
							String openId=userCurrent.getOpenidWa();
							String desc="微信支付退回";
							try {
								String a = WechatExtract.deptToUser(trueJine, openId, desc, id);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							/* 插入微信支付退回记录 */
							Money currentMoney = new Money();
							currentMoney.setOrderId(realId);
							currentMoney.setUserId(thisUserId);
							currentMoney.setJine(jine);
							currentMoney.setJilu("微信支付退回");
							currentMoney.setPayWay("5001");
							currentMoney.setValid(1);
							currentMoney.setCreactDate(DateUtils.getNowDate());
							currentMoney.setCreateBy(ShiroUtils.getSysUser()
									.getUserName());
							moneyService.insertMoney(currentMoney);


						}

						if ("5008".equals(payWay)) {
							/* QQ支付 退回到用户账户余额中 */
							Double jine = moneyPersist.getJine();
							jine=-jine;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine=jine-startFee;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine=(double) 0;
								}
							}

							String trueJine = jine.toString();
							//weixinMoney = weixinMoney.subtract(Decimaljine);
							/* 微信支付 退回 */
							int thisUserId = moneyPersist.getUserId();
							User userCurrent = userService
									.selectUserById(thisUserId);
							String openId=userCurrent.getOpenidWa();
							String desc="QQ支付退回";

							String a = QQPayExtract.deptToUser(trueJine, openId, desc, orderNo);

							/* 插入微信支付退回记录 */
							Money currentMoney = new Money();
							currentMoney.setOrderId(realId);
							currentMoney.setUserId(thisUserId);
							currentMoney.setJine(jine);
							currentMoney.setJilu("QQ支付退回");
							currentMoney.setPayWay("5008");
							currentMoney.setValid(1);
							currentMoney.setCreactDate(DateUtils.getNowDate());
							currentMoney.setCreateBy(ShiroUtils.getSysUser()
									.getUserName());
							moneyService.insertMoney(currentMoney);


						}
						if ("5002".equals(payWay)) {
							/* 余额支付 退回到用户账户余额中 */
							Double jine2 = moneyPersist.getJine();
							jine2=-jine2;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine2=jine2-startFee;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine2=(double) 0;
								}
							}
							credit1=credit1+jine2;
							backCredit1=backCredit1+jine2;
						}
						if ("5003".equals(payWay)) {
							/* 金币支付 退回到用户金币余额中 */
							Double jine3 = moneyPersist.getJine();
							jine3=-jine3;
							if("总金额".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额为全部总金额-配送费
									jine3=jine3-startFee*10;
								}
							} else if("小费".equals(record)) {
								//骑手Id不为空，则为已接单
								if(qishouId!=null){
									//已接单，退回金额需要减去小费
									jine3=(double) 0;
								}
							}
							credit2=credit2+jine3;
							backCredit2=backCredit2+jine3;
						}
						if ("5006".equals(payWay)) {
							/* 帮圈佣金 退回 */
							Double jine4 = moneyPersist.getJine();
							int thisUserId = moneyPersist.getUserId();

							/* 修改用户佣金 */
							User userCurrent = userService
									.selectUserById(thisUserId);
							Double commisson = userCurrent.getCommission();
							commisson = commisson - jine4;
							userCurrent.setCommission(commisson);
							userService.updateUser(userCurrent);

							/* 插入佣金退回记录 */
							Money currentMoney = new Money();
							currentMoney.setOrderId(realId);
							currentMoney.setUserId(thisUserId);
							currentMoney.setJine(-jine4);
							currentMoney.setJilu("佣金退回");
							currentMoney.setPayWay("5006");
							currentMoney.setValid(1);
							currentMoney.setNowMoney(commisson.toString());
							currentMoney.setCreactDate(DateUtils.getNowDate());
							currentMoney.setCreateBy(ShiroUtils.getSysUser()
									.getUserName());
							moneyService.insertMoney(currentMoney);
						}

					}

					/* 退回金额大于0 往money表插入记录 */
					if (backCredit1>0) {
						Money moneyPersist1 = new Money();
						moneyPersist1.setOrderId(realId);
						moneyPersist1.setUserId(userId);
						moneyPersist1.setJine(backCredit1);
						moneyPersist1.setPayWay("5002");
						moneyPersist1.setJilu("订单退货余额退回");
						moneyPersist1.setValid(1);
						moneyPersist1.setNowMoney(String.valueOf(credit1));
						moneyPersist1.setCreactDate(DateUtils.getNowDate());
						moneyPersist1.setCreateBy(ShiroUtils.getSysUser()
								.getUserName());
						moneyService.insertMoney(moneyPersist1);
					}

					if (backCredit2>0) {
						Money moneyPersist2 = new Money();
						moneyPersist2.setOrderId(realId);
						moneyPersist2.setUserId(userId);
						moneyPersist2.setJine(backCredit2);
						moneyPersist2.setPayWay("5003");
						moneyPersist2.setJilu("订单退货金币退回");
						moneyPersist2.setNowMoney(String.valueOf(credit2));
						moneyPersist2.setValid(1);
						moneyPersist2.setCreactDate(DateUtils.getNowDate());
						moneyPersist2.setCreateBy(ShiroUtils.getSysUser()
								.getUserName());
						moneyService.insertMoney(moneyPersist2);
					}
					userPersist.setCredit1(new BigDecimal(credit1));
					userPersist.setCredit2(new BigDecimal(credit2));
					userPersist.setUpdateBy(ShiroUtils.getSysUser()
							.getUserName());
					userPersist.setUpdateTime(DateUtils.getNowDate());
					userService.updateUser(userPersist);
				}



				/* 退回红包 */
				Integer HbId = orderPersist.getPacketsId();
				if (HbId != null) {
					HbUser hbUser = hbUserService.selectHbUserById(HbId);
					if (hbUser != null) {
						hbUser.setValid(1);
						hbUser.setModifyDate(DateUtils.getNowDate());
						hbUserService.updateHbUser(hbUser);
					}
				}

				/* 修改订单退款状态与审核时间 */
				Order persistOrder = orderService.selectOrderById(realId);
				persistOrder.setReturnOperate(1);
				persistOrder.setPassDate(DateTools.getYMDhms());
				persistOrder.setModifyBy(ShiroUtils.getSysUser().getUserName());
				persistOrder.setOrderShuxin("2008");
				persistOrder.setModifyDate(DateTools.getYMDhms());
//				weixin.fxx_nowfxx_now(String.valueOf(userId), orderNum, toUserSuccess);
//				if(riderId!=null){
//					weixin.fxx_now(String.valueOf(riderId), orderNum,
//							toRiderSuccess);
//				}

				return toAjax(orderService.updateOrder(persistOrder));
			} else if (returType.equals("3")) {
				/* 仅退货的情况 */
				/* 退回商品销量和库存数量 */

				OrderGoods oGoods = new OrderGoods();
				oGoods.setOrderId(realId);
				List<OrderGoods> OrderGoodslist = orderGoodsService
						.selectOrderGoodsList(oGoods);
				if (OrderGoodslist.size() > 0) {
					for (OrderGoods example : OrderGoodslist) {
						Integer num = example.getNum();
						Integer goodsId = example.getGoodsId();
						Goods persist = goodsService.selectGoodsById(goodsId);
						Integer goodsNum = persist.getGoodsNum();
						Integer goodsXl = persist.getGoodsXl();
						/* 修改库存 */
						goodsNum = goodsNum + num;
						/* 修改销量 */
						if(goodsXl!=null){
							goodsXl = goodsXl - num;
						} else {
							goodsXl = 0;
						}
						persist.setGoodsNum(goodsNum);
						persist.setGoodsXl(goodsXl);
						persist.setModifyBy(ShiroUtils.getSysUser()
								.getUserName());
						persist.setModifyDate(DateUtils.getNowDate());
						goodsService.updateGoods(persist);
					}
				}
				/* 修改订单退款状态与审核时间 */
				Order persistOrder = orderService.selectOrderById(realId);
				persistOrder.setReturnOperate(1);
				persistOrder.setPassDate(DateTools.getYMDhms());
				persistOrder.setModifyBy(ShiroUtils.getSysUser().getUserName());
				persistOrder.setModifyDate(DateTools.getYMDhms());
				persistOrder.setOrderShuxin("2008");
//				weixin.fxx_now(String.valueOf(userId), orderNum, toUserSuccess);
//				if(riderId!=null){
//					weixin.fxx_now(String.valueOf(riderId), orderNum,
//							toRiderSuccess);
//				}

				return toAjax(orderService.updateOrder(persistOrder));
			} else {
				return AjaxResult.error("退货类型不明 请联系管理员");
			}
		} else {
			return AjaxResult.error("订单未填写退货类型");
		}

		/*
		 * 退回商品销量和库存数量
		 *
		 * OrderGoods oGoods = new OrderGoods(); oGoods.setOrderId(realId);
		 * List<OrderGoods> OrderGoodslist = orderGoodsService
		 * .selectOrderGoodsList(oGoods); if (OrderGoodslist.size() > 0) { for
		 * (OrderGoods example : OrderGoodslist) { int num = example.getNum();
		 * int goodsId = example.getGoodsId(); Goods persist =
		 * goodsService.selectGoodsById(goodsId); int goodsNum =
		 * persist.getGoodsNum(); int goodsXl = persist.getGoodsXl(); 修改库存
		 * goodsNum = goodsNum + num; 修改销量 goodsXl = goodsXl + num;
		 * persist.setGoodsNum(goodsNum); persist.setGoodsXl(goodsXl);
		 * persist.setModifyBy(ShiroUtils.getSysUser().getUserName());
		 * persist.setModifyDate(DateUtils.getNowDate());
		 * goodsService.updateGoods(persist); } }
		 *
		 * 退回用户金币、余额以及红包(小费和跑腿费不退回)
		 *
		 * 找到用户当前金额 int userId = orderPersist.getUserId(); User userPersist =
		 * userService.selectUserById(userId); BigDecimal credit1 =
		 * userPersist.getCredit1(); BigDecimal credit2 =
		 * userPersist.getCredit2(); 找到并修改订单金额流向 Money moneyExample = new
		 * Money(); moneyExample.setOrderId(realId); List<Money> moneyList =
		 * moneyService.selectMoneyList(moneyExample); if (moneyList.size() > 0
		 * && moneyList != null) { for (Money moneyPersist : moneyList) { String
		 * payWay = moneyPersist.getPayWay(); if ("5001".equals(payWay)) { 微信支付
		 * 退回到用户账户余额中 Double jine = moneyPersist.getJine(); BigDecimal
		 * Decimaljine = new BigDecimal(jine); credit1 =
		 * credit1.add(Decimaljine); } if ("5002".equals(payWay)) { 余额支付
		 * 退回到用户账户余额中 Double jine2 = moneyPersist.getJine(); BigDecimal
		 * Decimaljine2 = new BigDecimal(jine2); credit1 =
		 * credit1.add(Decimaljine2); } if ("5003".equals(payWay)) { 金币支付
		 * 退回到用户金币余额中 Double jine3 = moneyPersist.getJine(); BigDecimal
		 * Decimaljine3 = new BigDecimal(jine3); credit2 =
		 * credit2.add(Decimaljine3); } } userPersist.setCredit1(credit1);
		 * userPersist.setCredit2(credit2);
		 * userPersist.setUpdateBy(ShiroUtils.getSysUser().getUserName());
		 * userPersist.setUpdateTime(DateUtils.getNowDate()); ;
		 * userService.updateUser(userPersist); }
		 *
		 * 退回红包 int HbId = orderPersist.getPacketsId(); HbUser hbUser =
		 * hbUserService.selectHbUserById(HbId); if (hbUser != null) {
		 * hbUser.setValid(1); hbUser.setModifyDate(DateUtils.getNowDate());
		 * hbUserService.updateHbUser(hbUser); }
		 *
		 * 修改订单退款状态与审核时间 Order persistOrder =
		 * orderService.selectOrderById(realId);
		 * persistOrder.setReturnOperate(1);
		 * persistOrder.setPassDate(DateTools.getYMDhms());
		 * persistOrder.setModifyBy(ShiroUtils.getSysUser().getUserName());
		 * persistOrder.setModifyDate(DateTools.getYMDhms());
		 * orderService.updateOrder(persistOrder); return
		 * AjaxResult.error("测试");
		 */
	}

	/**
	 * 订单审核 驳回申请
	 */
	@PostMapping("/updateStatus2")
	@ResponseBody
	public AjaxResult updateStatus2(String id) {
		/* 修改订单退款状态与审核时间 */

		String toUserFalse = "您申请的退款订单已驳回！";
		int realId = Integer.parseInt(id);
		Order persistOrder = orderService.selectOrderById(realId);
		int userId = persistOrder.getUserId();
		String orderNum = persistOrder.getOrderid();
		persistOrder.setReturnOperate(-1);
		persistOrder.setPassDate(DateTools.getYMDhms());
		persistOrder.setModifyBy(ShiroUtils.getSysUser().getUserName());
		persistOrder.setOrderShuxin("2008");
		persistOrder.setModifyDate(DateTools.getYMDhms());
//		try {
//			weixin.fxx_now(String.valueOf(userId), orderNum, toUserFalse);
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return toAjax(orderService.updateOrder(persistOrder));
	}

	//schoolId改拿部门Id
			public String getDeptId() {
				SysDept dept=ShiroUtils.getSysUser().getDept();
				if(dept!=null){
					String id=dept.getDeptId().toString();
					return id;
				} else {
					return StringUtils.EMPTY;
				}
			}
	//获得配送费
			/*public Double getStartFee() {
				SysDept dept=ShiroUtils.getSysUser().getDept();
				if(dept!=null){
					Integer id=dept.getSchoolId();
					School persistSchool=schoolService.selectSchoolById(id);
					Double startFee=persistSchool.getStartFee();
					return startFee;
				} else {
					return (double) 0;
				}
			}*/
			/*public Double getStartFee() {
				long l = Long.valueOf(deptId).longValue();
				SysDept dept=deptService.selectDeptById(l);
				if(dept!=null){
					int id=dept.getSchoolId();
					School persistSchool=schoolService.selectSchoolById(id);
					Double startFee=persistSchool.getStartFee();
					return startFee;
				} else {
					return (double)0;
				}
			}*/
}
